package atomic;

import atomic.counter.*;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 高并发、大数据量下的点赞设计
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/21 下午 07:05
 */
public class LikeCountTest {
    private static final int THREAD_NUM = 50;
    private static final int ROUND_NUM = 100 * 10000;

    private void doCount(final Counter counter) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(THREAD_NUM);

        long stime = System.currentTimeMillis();
        for (int i = 0; i < THREAD_NUM; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < ROUND_NUM; j++) {
                        counter.increment();
                    }
                } finally {
                    latch.countDown();
                }
            }).start();
        }

        latch.await();
        System.out.println(counter.getClass().getSimpleName() + "计数值为：" + counter.getCount());
        long etime = System.currentTimeMillis();
        System.out.println("---costTime：" + (etime - stime) + "ms");
    }


    @Test
    public void counterTest() throws Exception {
        doCount(new SynchronizedCounter());//1640ms
        doCount(new AtomicLongCounter());//1141ms
        doCount(new LongAdderCounter());//94ms
        doCount(new LongAccumulatorCounter());//78ms
    }
}
